<template>
  <div class="tw-libchart">
    <div v-show="data.length>0"
      class="tw-datasetchart"
      ref="chart"
      :style="{height: height, backgroundColor: bgColor}">
    </div>

    <tw-lib-nodata v-show="data.length===0" />
  </div>
</template>

<script>
import props from './props'
import chartMixins from '../tw-lib-base/chart/chart'

export default {
  name: 'chart-bar-plusminus',

  mixins: [chartMixins],

  props,

  data() {
    return {
      chartType: 'bar',
      avg: 0
    }
  },

  computed: {
    yNamePad () {
      if (this.yNamePadding instanceof Array) {
        return this.yNamePadding
      } else if (this.yNamePadding === '') {
        return []
      } else {
        let name = this.yNamePadding.split(',')
        let label = []
        for (let i = 0; i < name.length; i++) {
          if (name[i]) {
            label.push(parseInt(name[i]))
          } else {
            label.push(0)
          }
        }
        return label
      }
    },
    xNamePad () {
      if (this.xNamePadding instanceof Array) {
        return this.xNamePadding
      } else if (this.xNamePadding === '') {
        return []
      } else {
        let name = this.xNamePadding.split(',')
        let label = []
        for (let i = 0; i < name.length; i++) {
          if (name[i]) {
            label.push(parseInt(name[i]))
          } else {
            label.push(0)
          }
        }
        return label
      }
    },
    option () {
      let data = []
      this.avg = 0
      if (this.custAvg) {
        let fix = parseInt(this.avgFixed)
        let length = 0
        let ylength = 0
        let count = 0
        let sum = 0

        length = this.data.length
        if (length > 0) {
          ylength = this.data[0].length
        }


        for (let i = 1; i <= length - 1; i++) {
          for (let j = 1; j <= ylength - 1; j++) {
            sum += this.data[i][j]
            count += 1
          }
        }
        if (count > 0) {
          this.avg = (sum / count).toFixed(fix)
        }

        data = JSON.parse(JSON.stringify(this.data))
        for (let i = 1; i <= length - 1; i++) {
          for (let j = 1; j <= ylength - 1; j++) {
            data[i][j] = parseFloat((data[i][j] - this.avg).toFixed(fix))
          }
        }

        // data = this.data
      } else {
        data = this.data
      }
      let yAxis = {
        name: this.yName,
        nameTextStyle: {
          color: this.nameStyleColor,
          fontSize: this.nameStyleSize,
          padding: this.yNamePad.length > 0 ? this.yNamePad : null
        },
        type: this.yAxisType,
        minInterval: this.minInterval,
        show: this.showY,
        axisLine: {
          show: this.showYLine,
          lineStyle: {
            color: this.axisLineColor
          }
        },
        min: this.yAxisMin === '' ? null : this.yAxisMin,
        splitNumber: this.yAxisSplitNumber === '' ? null : this.yAxisSplitNumber,
        max: this.yAxisMax === '' ? null : this.yAxisMax,
        axisTick: {
          show: this.showYAxisTick
        },
        axisLabel: {
          show: true,
          formatter: this.custAvg ? this.funCustAvg : (this.useYAxisFun ? this.funcYAxisLabel : ('{value}' + this.yLabel)),
          rotate: this.yLabelRotate,
          interval: this.axisTickInterval === '' ? 'auto' : parseInt(this.axisTickInterval),
          textStyle: {
            fontSize: this.axisLabelFontSize,
            color: this.axisLabelColor
          }
        },
        splitLine: {
          show: this.showSplitLine,
          lineStyle: {
            color: [
              this.splitLineColor
            ]
          }
        }
      }
      return {
        title: {
          show: this.showTitle,
          text: this.titleText,
          subtext: this.subtitleText
        },
        color: this.colors,
        legend: {
          show: this.showLegend,
          left: this.legendLeft === '' ? 'auto' : this.legendLeft,
          top: this.legendTop === '' ? 'auto' : this.legendTop,
          right: this.legendRight === '' ? 'auto' : this.legendRight,
          bottom: this.legendBottom === '' ? 'auto' : this.legendBottom,
          itemHeight: parseInt(this.legendHeight),
          itemWidth: parseInt(this.legendWidth),
          icon: this.icon,
          textStyle: {
            color: this.legendColor,
            fontSize: this.legendFontSize,
            padding: [3, 0, 0, 0]
          }
        },
        grid: {
          show: this.showGrid,
          left: this.gridLeft === '' ? 'auto' : this.gridLeft,
          top: this.gridTop === '' ? 'auto' : this.gridTop,
          right: this.gridRight === '' ? 'auto' : this.gridRight,
          bottom: this.gridBottom === '' ? 'auto' : this.gridBottom,
          borderWidth: 0,
          containLabel: true
        },
        tooltip: {
          trigger: this.triggerType,
          confine: this.confine,
          extraCssText: this.confine ? 'white-space: normal; word-break: break-all;' : '',
          formatter: this.useTooltipFun ? this.tooltipFunction : this.tooltipLabel
        },
        dataZoom: this.showDataZoom ? {
          start: this.dataZoomStart,
          end: this.dataZoomEnd,
          type: this.dataZoomType,
          xAxisIndex: this.xAxisType === 'category' ? 0 : null,
          yAxisIndex: this.yAxisType === 'category' ? 0 : null
        } : null,
        xAxis: this.showAxis ? {
          type: this.xAxisType,
          show: this.showX,
          name: this.xName,
          nameTextStyle: {
            color: this.nameStyleColor,
            fontSize: this.nameStyleSize,
            padding: this.xNamePad.length > 0 ? this.xNamePad : null
          },
          boundaryGap: this.boundaryGap,
          axisLine: {
            show: this.showXLine,
            lineStyle: {
              type: this.axisLineType,
              color: this.axisXLineColor
            }
          },
          axisTick: {
            show: this.showXAxisTick,
          },
          axisLabel: {
            show: true,
            formatter: this.xAxisType === 'value' ? '{value}' + this.yLabel : (this.useXAxisFun ? this.axisFunction : '{value}'),
            rotate: this.xLabelRotate,
            interval: this.axisTickInterval === '' ? 'auto' : parseInt(this.axisTickInterval),
            textStyle: {
              fontSize: this.axisLabelFontSize,
              color: this.axisLabelColor
            }
          },
          splitLine: {
            lineStyle: {
              color: [
                this.splitLineColor
              ]
            }
          }
        } : null,
        yAxis: this.showAxis ? yAxis : null,
        dataset: {
          source: data
        },
        series: this.series
      }
    }
  },

  methods: {
    setSeries () {
      let vm = this
      let length = 0
      if (this.seriesIsRow) {
        length = this.data.length
      } else {
        if (this.data.length > 0) {
          length = this.data[0].length
        } else {
          length = 0
        }
      }
      this.series = []
      for (let i = 0; i < length - 1; i++) {
        let series = {}
        if (length === 2) {
          series = {
            type: this.chartType,
            label: {
              show: this.showBarLabel,
              fontSize: this.barFontSize,
              position: this.barPosition,
            },
            itemStyle: {
              color: function (params) {
                return vm.colors[params.dataIndex]
              }
            },
            barMaxWidth: this.barMaxWidth,
            seriesLayoutBy: this.seriesIsRow ? 'row' : 'column'
          }
        } else {
          series = {
            type: this.chartType,
            label: {
              show: this.showLabel,
              fontSize: this.labelFontSize,
              position: this.labelPosition,
            },
            barMaxWidth: this.barMaxWidth,
            seriesLayoutBy: this.seriesIsRow ? 'row' : 'column'
          }
        }

        let cusSeries = {}
        if (this.useSeries && this.funcSeries !== '' && typeof this.funcSeries === 'function') {
          cusSeries = this.funcSeries(i, this)
        }
        Object.assign(series, {}, cusSeries)
        this.series.push(series)
      }

      if (this.extendOption && this.funcExtOption !== '' && typeof this.funcExtOption === 'function') {
        this.funcExtOption(this)
      }
    },
    tooltipFunction (params) {
      let label = ''
      if (this.funcTooltip !== '' && typeof this.funcTooltip === 'function') {
        let func1 = this.funcTooltip
        label = func1(params, this)
      }
      return label
    },
    funCustAvg (params) {
      return parseFloat(parseFloat(params) + parseFloat(this.avg)).toFixed(parseInt(this.avgFixed)) + '' + this.yLabel
    }
  },

  watch: {
    seriesIsRow () {
      this.setSeries()
    },

    barMaxWidth () {
      this.setSeries()
    },

    extendOption () {
      this.setSeries()
    },
    useSeries () {
      this.setSeries()
    }
  }
}
</script>

<style lang="scss">
  @import './css/index.scss';
</style>
